package com.yj.consumer.dynamicDataSource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.processing.Processor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
@Order(1)
public class DataSourceAop {


    @Pointcut(value = "@annotation(com.yj.consumer.dynamicDataSource.DataSourceChoose)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method =
                methodSignature.getMethod();
        DataSourceChoose annotation = method.getAnnotation(DataSourceChoose.class);
        String value = annotation.value();
        DynamicDataSource.setDataSourceContext(value);
        try {
            return joinPoint.proceed();
        } finally {
            DynamicDataSource.remove();
        }

    }
}
